package com.egd.imapp.contoller.fragment;


import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import com.egd.imapp.R;
import com.egd.imapp.contoller.activity.chat.GroupChatActivity;
import com.egd.imapp.contoller.activity.chat.SingleChatActivity;
import com.egd.imapp.contoller.activity.contact.AddFriendActivity;
import com.egd.imapp.contoller.activity.contact.GroupListActivity;
import com.egd.imapp.utils.CustomDialog;
import com.egd.imapp.utils.DevicePopWindow;
import com.hyphenate.EMMessageListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.chat.EMGroup;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.easeui.EaseIM;
import com.hyphenate.easeui.constants.EaseConstant;
import com.hyphenate.easeui.domain.EaseUser;
import com.hyphenate.easeui.manager.EaseSystemMsgManager;
import com.hyphenate.easeui.modules.conversation.EaseConversationListFragment;
import com.hyphenate.easeui.modules.conversation.model.EaseConversationInfo;
import com.hyphenate.easeui.utils.EaseCommonUtils;
import com.hyphenate.easeui.widget.EaseSearchTextView;
import com.hyphenate.easeui.widget.EaseTitleBar;

import java.util.List;

public class ConversationListFragment extends EaseConversationListFragment {
    private ImageView iv_conversation_add;
    private EaseSearchTextView tvSearch;
    private DevicePopWindow devicePopWindow;

    private static final String TAG = "ChatListFragment";

    @Override
    public void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);

        addCommonTitle();

        //设置无数据时空白页面
        conversationListLayout.getListAdapter().setEmptyLayoutId(R.layout.imapp_layout_contact_list_empty);

    }

    @Override
    public void initData() {
        super.initData();
    }

    @Override
    public void initListener() {
        super.initListener();

        // 监听会话消息
        EMClient.getInstance().chatManager().addMessageListener( eMessageListener);

        iv_conversation_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                devicePopWindow.showAsDropDown(iv_conversation_add);
            }
        });

    }

    private EMMessageListener eMessageListener = new EMMessageListener() {
        @Override
        public void onMessageReceived(List<EMMessage> messages) {
            // 设置数据
            EaseIM.getInstance().getNotifier().notify(messages);

            // 刷新页面
            onRefresh();

        }

        @Override
        public void onCmdMessageReceived(List<EMMessage> messages) {

        }

        @Override
        public void onMessageRead(List<EMMessage> messages) {

            onRefresh();
        }

        @Override
        public void onMessageDelivered(List<EMMessage> messages) {

        }

        @Override
        public void onMessageRecalled(List<EMMessage> messages) {

        }

        @Override
        public void onMessageChanged(EMMessage message, Object change) {
            onRefresh();
        }
    };


    // 跳转到会话详情页面
    @Override
    public void onItemClick(View view, int position) {
        super.onItemClick(view, position);

        Object item = conversationListLayout.getItem(position).getInfo();

        if(item instanceof EMConversation) {
            if(EaseSystemMsgManager.getInstance().isSystemConversation((EMConversation) item)) {
                Toast.makeText(mContext, "系统消息 ", Toast.LENGTH_SHORT).show();

//                SystemMsgsActivity.actionStart(mContext);
            }else {
                String conversationId = ((EMConversation)item).conversationId();
                switch (EaseCommonUtils.getChatType((EMConversation) item)){
                    case EaseConstant.CHATTYPE_SINGLE: // 单聊
                        startSingleChat(conversationId);
                        break;
                    case EaseConstant.CHATTYPE_GROUP: // 群聊
                        startGroupChat(conversationId);
                        break;
                }
            }

            Log.e(TAG, "onItemClick: 会话人：position = "+ position + " item = " + item );
        }

    }

    private void startGroupChat(String conversationId) {
        Intent intent = new Intent(mContext, GroupChatActivity.class);

        intent.putExtra(EaseConstant.EXTRA_CHAT_TYPE, EaseConstant.CHATTYPE_GROUP);

        intent.putExtra(EaseConstant.EXTRA_CONVERSATION_ID, conversationId);

        startActivity(intent);
    }

    private void startSingleChat(String conversationId) {
        EaseUser user = new EaseUser();
        user.setUsername(conversationId);
        user.setNickname(conversationId);
        user.setSign(conversationId);

        Intent intent = new Intent(mContext, SingleChatActivity.class);
        intent.putExtra("user", user);
        startActivity(intent);
    }

    private void addCommonTitle() {
        View view = LayoutInflater.from(mContext).inflate(R.layout.imapp_layout_common_tilte, null);
        llRoot.addView(view,0);
        iv_conversation_add = view.findViewById(R.id.iv_contact_add);
        EaseTitleBar common_titlebar = view.findViewById(R.id.common_titlebar);
        common_titlebar.setTitle("会 话");
        tvSearch = view.findViewById(R.id.tv_search);
        addPopuWindow();
    }

    /**
     * 初始化PopuWindow，并对其中的子view 设置点击监听
     */
    private void addPopuWindow() {
        devicePopWindow = new DevicePopWindow(mContext, R.layout.pop_window_device);
        View view = devicePopWindow.getContentView();

        view.findViewById(R.id.tv_contact_add_friend).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) { // 添加好友
                Intent intent = new Intent(mContext, AddFriendActivity.class);
                startActivity(intent);
            }
        });
        view.findViewById(R.id.tv_contact_find_group).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {// 找群
                Toast.makeText(mContext, "服务完善中...", Toast.LENGTH_SHORT).show();

            }
        });
        view.findViewById(R.id.tv_contact_scan).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {// 扫一扫
                Toast.makeText(mContext, "服务完善中...", Toast.LENGTH_SHORT).show();

            }
        });

    }

    @Override
    public boolean onMenuItemClick(MenuItem item, int position) {
        EaseConversationInfo info = conversationListLayout.getItem(position);
        Object object = info.getInfo();

        if(object instanceof EMConversation) {
            switch (item.getItemId()) {
                case R.id.action_con_make_top :
                    conversationListLayout.makeConversationTop(position, info);
                    return true;
                case R.id.action_con_cancel_top :
                    conversationListLayout.cancelConversationTop(position, info);
                    return true;
                case R.id.action_con_delete :
                    showDeleteDialog(position, info);
                    Toast.makeText(mContext, "action_con_delete 删除会话 ", Toast.LENGTH_SHORT).show();

                    return true;
            }
        }
        return super.onMenuItemClick(item, position);
    }


    private void showDeleteDialog(int position, EaseConversationInfo info) {
        CustomDialog customDialog = new CustomDialog(mContext);
        customDialog.setMsg("删除会话")
                .setNegative("取消")
                .setPositive("确定")
                .setOnClickButtonListener(new CustomDialog.OnClickButtonListener() {
                    @Override
                    public void OnClickNegative() {
                        customDialog.dismiss();
                    }

                    @Override
                    public void OnClickPositive() {
                        conversationListLayout.deleteConversation(position, info);
                        customDialog.dismiss();
                    }
                }).show();
    }

    @Override
    public void onResume() {
        super.onResume();
        onRefresh();
    }
}